package com.kamistoat.ruoyi.ruoyimodulessystem.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kamistoat.ruoyi.ruoyiapisystem.domain.SysUser;
import com.kamistoat.ruoyi.ruoyiapisystem.entity.SysUserEntity;
import com.kamistoat.ruoyi.ruoyiapisystem.feign.RemoteFileService;
import com.kamistoat.ruoyi.ruoyicommoncore.utils.StringUtils;
import com.kamistoat.ruoyi.ruoyicommoncore.web.controller.BaseController;
import com.kamistoat.ruoyi.ruoyicommoncore.web.domain.AjaxResult;
import com.kamistoat.ruoyi.ruoyicommonlog.annotation.Log;
import com.kamistoat.ruoyi.ruoyicommonlog.enums.BusinessType;
import com.kamistoat.ruoyi.ruoyicommonsecurity.utils.SecurityUtils;
import com.kamistoat.ruoyi.ruoyicommonsecurity.utils.TokenUtils;
import com.kamistoat.ruoyi.ruoyimodulessystem.service.SysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * 个人信息业务。独立在 SYSUserController之外。前者是管理全部用户，这里是个人用户
 */
@RestController
@RequestMapping("/user/profile")
public class SysProfileController extends BaseController {
    @Autowired
    SysUserService sysUserService;
    @Autowired
    TokenUtils tokenUtils;
    @Autowired
    RemoteFileService remoteFileService;


    /**
     * 个人信息
     */
    @GetMapping
    public AjaxResult profile() {
        String username = SecurityUtils.getUserName();
        SysUserEntity userEntity = sysUserService.getOne(new QueryWrapper<SysUserEntity>().eq("user_name", username));
        AjaxResult ajax = AjaxResult.success(entity2Vo(userEntity));
        // 以逗号链接返回名称组
        ajax.put("roleGroup", SecurityUtils.getLoginUser().getRoles().stream().collect(Collectors.joining(",")));
        ajax.put("postGroup", SecurityUtils.getLoginUser().getPosts().stream().collect(Collectors.joining(",")));
        return ajax;
    }

    /**
     * 修改个人信息
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult updateProfile(@RequestBody SysUser user) {
        SysUser cacheSysUser = SecurityUtils.getLoginUser().getSysUser();
        if (!cacheSysUser.getUserId().equals(user.getUserId())) {
            return AjaxResult.error("数据校验异常，请重新登录后再尝试修改");
        }

        // 自己改自己。前端也只提供这三个修改
        if (sysUserService.checkUserNameUnique(user)) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，该账号名称已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber())
                && sysUserService.checkPhoneUnique(user)) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && sysUserService.checkEmailUnique(user)) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }

        SysUserEntity one = new SysUserEntity();
        one.setUserId(cacheSysUser.getUserId());
        one.setUserName(user.getUserName());
        one.setPhonenumber(user.getPhonenumber());
        one.setEmail(user.getEmail());
        boolean updateOne = sysUserService.updateById(one);

        if (updateOne) {
            tokenUtils.updateCoreLoginUserCacheOnLine(Arrays.asList(cacheSysUser.getUserId()));
            return AjaxResult.success();
        }
        return AjaxResult.error("修改个人信息异常，请联系管理员");
    }

    /**
     * 重置密码
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePwd")
    public AjaxResult updatePwd(String oldPassword, String newPassword) {
        String username = SecurityUtils.getUserName();
        SysUserEntity user = sysUserService.getOne(new QueryWrapper<SysUserEntity>().eq("user_name", username));
        // 数据库中的加密密码
        String password = user.getPassword();

        if (!SecurityUtils.matchesPassword(oldPassword, password)) {
            return AjaxResult.error("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password)) {
            return AjaxResult.error("新密码不能与旧密码相同");
        }

        SysUserEntity one = new SysUserEntity();
        one.setUserId(SecurityUtils.getUserId());
        one.setPassword(SecurityUtils.encryptPassword(newPassword));
        boolean updateOne = sysUserService.updateById(one);
        // 密码不进行缓存
        if (updateOne) {
            return AjaxResult.success();
        }
        return AjaxResult.error("修改密码异常，请联系管理员");
    }

    /**
     * 头像上传.设计文件服务。
     */
    @Log(title = "用户头像", businessType = BusinessType.UPDATE)
    @PostMapping("/avatar")
    public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) {
//        if (!file.isEmpty()) {
//            LoginUser loginUser = SecurityUtils.getLoginUser();
//            String extension = FileTypeUtils.getExtension(file);
//            if (!StringUtils.equalsAnyIgnoreCase(extension, MimeTypeUtils.IMAGE_EXTENSION)) {
//                return AjaxResult.error("文件格式不正确，请上传" + Arrays.toString(MimeTypeUtils.IMAGE_EXTENSION) + "格式");
//            }
//            R<SysFile> fileResult = remoteFileService.upload(file);
//            if (StringUtils.isNull(fileResult) || StringUtils.isNull(fileResult.getData())) {
//                return AjaxResult.error("文件服务异常，请联系管理员");
//            }
//            String url = fileResult.getData().getUrl();
//            if (userService.updateUserAvatar(loginUser.getUsername(), url)) {
//                AjaxResult ajax = AjaxResult.success();
//                ajax.put("imgUrl", url);
//                // 更新缓存用户头像
//                loginUser.getSysUser().setAvatar(url);
//                tokenService.setLoginUser(loginUser);
//                return ajax;
//            }
//        }
        return AjaxResult.error("上传图片异常，请联系管理员");
    }

    private SysUser entity2Vo(SysUserEntity sysUserEntity) {
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(sysUserEntity, sysUser);
        return sysUser;
    }

    private SysUserEntity vo2Entity(SysUser sysUser) {
        SysUserEntity sysUserEntity = new SysUserEntity();
        BeanUtils.copyProperties(sysUser, sysUserEntity);
        return sysUserEntity;
    }

}
